# -*- coding:utf-8 -*-
from application import app, db
from flask import Blueprint, jsonify, g
from common.models.admin.erp_menu import ErpMenu
from common.models.admin.erp_role_menu import ErpRoleMenu
from sqlalchemy import and_, or_

route_menu = Blueprint('menu_page', __name__)


@route_menu.route("/admin.go", methods=["GET", "POST"])
def adminMenu():
    resp = {'code': 200, 'msg': 'ok~~', 'data': {}}

    role_info = g.current_role

    resp['data'] = getMenus(role_info.id, '0')

    response = jsonify(resp)  # json.dumps(resp)
    return response


def getMenus(rid, pid):
    resData = []
    reschild = []
    menu = {}

    menus = ErpMenu.query.filter_by(pid=pid).order_by(ErpMenu.id.asc()).all()
    if not menus:
        return resData
    for item in menus:
        exists = db.session.query(ErpRoleMenu).filter(
            and_(ErpRoleMenu.rid == rid, or_(ErpRoleMenu.uid == item.id, ErpRoleMenu.uid == '0'))).count()
        if exists != 1:
            continue
        if item.status != 1:
            continue
        menu['id'] = item.id
        menu['title'] = item.title
        menu['icon'] = item.icon
        if item.last == 1:
            menu['href'] = item.href
        menu['notice'] = item.notice
        if item.last != 1:
            reschild = getMenus(rid, item.id)
            if len(reschild) > 0:
                menu['childs'] = reschild

        resData.append(menu)
        menu = {}
    return resData
